package com.t373.aop;

import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

/**
 * 事务的切面,专门用来管理事务(增删改 Pet  Goods User xxxxx......)
 * @author Jane
 * @date 2024-12-17 16:11
 */
@Aspect
@Component
public class TransactionAspect {
    private  static Logger log=Logger.getLogger(TransactionAspect.class);

    //切点规则
    @Pointcut("execution(* com.t373.service..*(..))")
    public void pointcut(){}

    @Before(value="pointcut()")
    public void before(JoinPoint joinPoint){
        log.info("[前置增强B]--打开数据库连接,并开启事务");
    }

    @AfterReturning(value ="pointcut()",returning = "result")
    public void afterReturning(JoinPoint jp,Object result){
        log.info("[后置增强B]--,并提交事务");
    }

    @AfterThrowing(value ="pointcut()",throwing = "e")
    public void afterThrowing(JoinPoint jp,Throwable e){
        log.info("[异常增强B]--记录日志,并回滚事务");
    }
    @After(value ="pointcut()")
    public void after(JoinPoint jp){

        log.info("[最终增强B]--关闭数据库连接,并事务提交");
    }

    @Around(value="pointcut()")
    public Object around(ProceedingJoinPoint jp) throws Throwable{
        log.info("[环绕增强--前置]--");
        //记录方法的执行时间
        long start=System.currentTimeMillis();

        try {
            Object res = jp.proceed();//负责执行目标方法
            System.out.println("方法的返回值:"+res);
            return res;
        } catch (Throwable e) {
            //throw new RuntimeException(e);
            log.info("[环绕增强--抛出异常]--"+e.getMessage());
            throw e;
        }finally {
            long end=System.currentTimeMillis();//结束时间
            log.info("[环绕增强--后置],执行时间:"  +  (start-end));
        }

    }
}
